<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class M_message Extends MY_Model
{
	public function get_all_employees()
	{

		foreach(range('a','z') as $letter)
		{
			$result = $this->_get_all_employees($letter);
			if($result)
			{
				$input[strtoupper($letter)] = $result;
			}

		}

		if($input)
		{
			return $input;
		}else{
			return FALSE;
		}
	}

	private function _get_all_employees($letter)
	{
		$sql = 'SELECT emp_id,
			   concat_ws("",last_name," , ",first_name," ",middle_name) as employee
			FROM employees 
			WHERE userStatus = "active"
			AND last_name like ?
			ORDER BY last_name';
		$q = $this->db->query($sql,[$letter.'%']);

		if($q->num_rows() >= 1)
		{
			foreach ($q->result() as $key => $value) {
				$return[$value->emp_id] = ucwords(strtolower($value->employee));
			}
			
			return $return;

			// return $this->db->last_query();
		}else{
			return FALSE;
		}
	}

	public function _get_legal_students($letter)
	{
		$sql = 'SELECT concat_ws("",p.lastname," , ",p.firstname," ",p.middlename) as fullname,
					   bs.block_name as block,
					   e.e_id as enrollment_id,
					   e.e_section_id,
					   p.dob,
					   p.gender,
					   lv.level_desc,
					   p.profile_id
				FROM enrollments e
				LEFT JOIN profiles p ON e.e_profile_id = profile_id
				LEFT JOIN block_section bs ON e.block = bs.id
				LEFT JOIN levels lv ON e.e_grade_level = lv.level_id
				WHERE e.e_ay_id = ?
				AND e.registrar_approved = 1
				AND e.verified = 1
				AND p.lastname like ?
				ORDER BY p.lastname,p.firstname';	
		$q = $this->db->query($sql,[$this->c_sy->id,$letter.'%']);
		
		if($q->num_rows() >= 1 )
		{
			foreach($q->result() as $k => $v)
			{
				$student[$v->profile_id] = ucwords(strtolower($v->fullname));
			}

			return $student;
		}else{
			return FALSE;
		}
	}
	
	public function _get_legal_students_under_employee($letter,$id)
	{
		$sql = 'SELECT concat_ws("",p.lastname," , ",p.firstname," ",p.middlename) as fullname,
					   bs.block_name as block,
					   e.e_id as enrollment_id,
					   e.e_section_id,
					   p.dob,
					   p.gender,
					   lv.level_desc,
					   p.profile_id
				FROM enrollments e
				LEFT JOIN profiles p ON e.e_profile_id = profile_id
				LEFT JOIN block_section bs ON e.block = bs.id
				LEFT JOIN levels lv ON e.e_grade_level = lv.level_id
				LEFT JOIN sections s ON e.e_section_id = s.id
				WHERE e.e_ay_id = ?
				AND e.registrar_approved = 1
				AND e.verified = 1
				AND p.lastname like ?
				AND s.adviser_id = ?
				ORDER BY p.lastname,p.firstname';	
		$q = $this->db->query($sql,[$this->c_sy->id,$letter.'%',$id]);
		//pd($this->db->last_query());
		if($q->num_rows() >= 1 )
		{
			foreach($q->result() as $k => $v)
			{
				$student[$v->profile_id] = ucwords(strtolower($v->fullname));
			}

			return $student;
		}else{
			return FALSE;
		}
	}

	public function get_legal_students($id='')
	{
		$input = '';
		
		if($id){
			foreach(range('a','z') as $letter)
			{
				$result = $this->_get_legal_students_under_employee($letter,$id);
				if($result)
				{
					$input[strtoupper($letter)] = $result;
				}
			}
		}else{
			foreach(range('a','z') as $letter)
			{
				$result = $this->_get_legal_students($letter);
				if($result)
				{
					$input[strtoupper($letter)] = $result;
				}
			}
		}

		if($input)
		{
			return $input;
		}else{
			return FALSE;
		}
	}
	
	
	public function _get_legal_parents($letter,$id=FALSE,$sy=FALSE)
	{
		$sql = 'SELECT u.id, u.username, profiles.fathername, profiles.mothername
				FROM users u
				LEFT JOIN parent_child p ON u.id = p.user_id
				LEFT JOIN enrollments e ON e.e_profile_id = p.p_id
				LEFT JOIN profiles ON profiles.profile_id = p.p_id
				WHERE u.userType = ?
				AND profiles.lastname like ?
				AND u.userStatus = ?
				AND e.e_ay_id = ?
				ORDER BY profiles.lastname';
		//if($sy){
			//$q = $this->db->query($sql,['user',$letter.'%','active',$sy]);
		//}else{
			$q = $this->db->query($sql,['user',$letter.'%','active',$this->c_sy->id]);
		//}

		if($q->num_rows() >= 1 )
		{
			foreach($q->result() as $k => $v)
			{
				$parent[$v->id] = ucwords(strtolower($v->username)).' [ '.ucwords(strtolower($v->fathername)).' , '.ucwords(strtolower($v->mothername)).' ]';
			}

			return $parent;
		}else{
			return FALSE;
		}
	}
	
	public function _get_legal_parents_under_employee($letter,$id,$sy=FALSE)
	{
		$sql = 'SELECT u.id, u.username, profiles.fathername, profiles.mothername
				FROM users u
				LEFT JOIN parent_child p ON u.id = p.user_id
				LEFT JOIN enrollments e ON e.e_profile_id = p.p_id
				LEFT JOIN profiles ON profiles.profile_id = p.p_id
				LEFT JOIN sections s ON s.id = e.e_section_id
				WHERE u.userType = ?
				AND profiles.lastname like ?
				AND u.userStatus = ?
				AND e.e_ay_id = ?
				AND s.adviser_id= ?
				ORDER BY profiles.lastname';
				
		//if($sy){
			//$q = $this->db->query($sql,['user',$letter.'%','active',$sy,$id]);
		//}else{
			$q = $this->db->query($sql,['user',$letter.'%','active',$this->c_sy->id,$id]);
			//pd($this->db->last_query());
		//}
		
		if($q->num_rows() >= 1 )
		{
			foreach($q->result() as $k => $v)
			{
				$parent[$v->id] = ucwords(strtolower($v->username)).' [ '.ucwords(strtolower($v->fathername)).' , '.ucwords(strtolower($v->mothername)).' ]';
			}

			return $parent;
		}else{
			return FALSE;
		}
	}
	
	public function get_legal_parents($id='',$sy=FALSE)
	{
		$input = '';
				
		if($id){
			foreach(range('a','z') as $letter)
			{
				$result = $this->_get_legal_parents_under_employee($letter,$id,$sy);
				if($result)
				{
					$input[strtoupper($letter)] = $result;
				}
			}
		}else{
			foreach(range('a','z') as $letter)
			{
				$result = $this->_get_legal_parents($letter,FALSE,$sy);
				if($result)
				{
					$input[strtoupper($letter)] = $result;
				}
			}
		}

		if($input)
		{
			return $input;
		}else{
			return FALSE;
		}

	}

	public function get_all_levels()
	{
		$sql = 'SELECT level_id,level_desc FROM levels WHERE level_stat = "active"';
		$q = $this->db->query($sql);


		if($q->num_rows() >= 1 )
		{
			foreach ($q->result() as $key => $value) {
				$level[$value->level_id] = $value->level_desc;
			}
			return $level;
		}else{
			return FALSE;
		}
	}

	public function get_all_sections($id='')
	{
		if($id){
			$levels = $this->get_all_levels();
			
			if($levels)
			{
				foreach($levels as $k => $v)
				{
					$sections[ucwords(strtolower($v))] = $this->_get_all_sections_under_employee($k,$id);
				}

				return $sections;
			}else{
				return FALSE;
			}
		}else{
			$levels = $this->get_all_levels();

			if($levels)
			{
				foreach($levels as $k => $v)
				{
					$sections[ucwords(strtolower($v))] = $this->_get_all_sections($k);
				}

				return $sections;
			}else{
				return FALSE;
			}
		}
	}

	private function _get_all_sections($level_id)
	{

		$sql = 'SELECT id,section_name
				FROM sections 
				WHERE grade_level_id = ?
				AND section_status = "active"';
		$q = $this->db->query($sql,[$level_id]);


		if($q->num_rows() >= 1 )
		{
			foreach ($q->result() as $key => $value) {
				$section[$value->id] = $value->section_name;
			}
			return $section;
		}else{
			return FALSE;
		}
	}
	
	private function _get_all_sections_under_employee($level_id,$emp_id)
	{

		$sql = 'SELECT id,section_name
				FROM sections 
				WHERE grade_level_id = ?
				AND adviser_id = ?
				AND section_status = "active"';
		$q = $this->db->query($sql,[$level_id,$emp_id]);


		if($q->num_rows() >= 1 )
		{
			foreach ($q->result() as $key => $value) {
				$section[$value->id] = $value->section_name;
			}
			return $section;
		}else{
			return FALSE;
		}
	}



	/*============================
		PROCESS SEND MESSAGE
	==============================*/

	public function process_message($post)
	{
		set_time_limit(0);

		$emp_id = $this->c_user->emp_id;

		$level = [];
		$section = [];
		$student = [];
		$parents = [];
		$employees = [];

		// pd($post);
		if(isset($post['level']))
		{
			if($post['level'])
			{
				$level = $this->_process_levels($post['level']);
			}
		}

		if(isset($post['section']))
		{
			if($post['section'])
			{
				$section = $this->_process_section($post['section']);
			}							
		}

		if(isset($post['students']))
		{
			if($post['students'])
			{
				// $student = $this->_process_student($post['students']);	
				$student = $post['students'];
			}
			
		}
		
		if(isset($post['parents']))
		{
			if($post['parents'])
			{
				// $student = $this->_process_student($post['students']);	
				$parents = $post['parents'];
			}
			
		}

		if(isset($post['employees']))
		{
			if($post['employees'])
			{
				$employees = $post['employees'];	
				// $employees = $this->_employees($post['employees']);	
			}
		}


		
		/*===============================================
		//create message thread
		================================================*/
		$message_thread['title'] = $post['title'];
		$message_thread['status'] = 'open';
		$message_thread['sender_id'] = $this->c_user->emp_id;
		$message_thread['senders_name'] = $this->_get_name($this->c_user->emp_id,'employees');
		$message_thread['created'] = NOW;


		$this->db->insert('message_thread',$message_thread);
		$thread_id = $this->db->insert_id();
		// pd($message_thread);
		
		/*===============================================
		//create message persons
		================================================*/
		
		$students_final = array_unique(array_merge($level,$section,$student));

		if($students_final)
		{
			foreach($students_final as $k => $v)
			{
				$student_to_persons[$k]['user'] = $v;
				$student_to_persons[$k]['thread_id'] = $thread_id;
				$student_to_persons[$k]['type'] = 'student';
				// $student_to_persons[$k]['is_sender'] = 0;
				$student_to_persons[$k]['senders_name'] = $this->_get_name($v,'student');
			}
		}else{
			$student_to_persons = [];
		}

		if($employees)
		{
			foreach($employees as $k => $v)
			{
				$emp_to_persons[$k]['user'] = $v;
				$emp_to_persons[$k]['thread_id'] = $thread_id;
				$emp_to_persons[$k]['type'] = 'employee';
				// $emp_to_persons[$k]['is_sender'] = 0;
				$emp_to_persons[$k]['senders_name'] = $this->_get_name($v,'employee');
			}
		}else{
			$emp_to_persons = [];
		}
		
		if($parents)
		{
			foreach($parents as $k => $v)
			{
				$parents_to_emp[$k]['user'] = $v;
				$parents_to_emp[$k]['thread_id'] = $thread_id;
				$parents_to_emp[$k]['type'] = 'guardian';
				// $emp_to_persons[$k]['is_sender'] = 0;
				$parents_to_emp[$k]['senders_name'] = $this->_get_name($v,'guardian');
			}
		}else{
			$parents_to_emp = [];
		}
		
		/*===============================================
		//insert all person that will recieve the message
		================================================*/
		$final_persons = array_merge($emp_to_persons,$student_to_persons,$parents_to_emp);
		if($final_persons){
			$this->db->insert_batch('message_person',$final_persons); 
		}

		//check if the sender is also selected

		$test_message = 'SELECT user FROM message_person WHERE user = ? AND thread_id = ?';
		$test = $this->db->query($test_message,[$emp_id,$thread_id]);

		if($test->num_rows() >=1)
		{
			//if the sender is also selected do nothing
		}else{
			//if the sender is not selected we add the sender to the list of message recievers
			$sender['user'] = $emp_id;
			$sender['thread_id'] = $thread_id;
			$sender['type'] = 'employee';
			$sender['senders_name'] = $this->_get_name($emp_id,'employee');

			$this->db->insert('message_person',$sender);
		}


		/*===============================================
		//create message contents
		================================================*/
		$message_data['contents'] = htmlentities($post['message_body']);
		$message_data['attachments'] = '';
		$message_data['thread_id'] = $thread_id;
		$message_data['created'] = NOW;
		$message_data['created_by'] = $this->c_user->emp_id;
		$message_data['type'] ='employee';

		$this->db->insert('message_data',$message_data);

		return $this->db->affected_rows()>=1 ? TRUE : FALSE;


	}

	private function _process_levels($levels)
	{
		$level_ids = "'". implode("', '", $levels) ."'";

		$l_eids = "SELECT e_id
				   FROM enrollments
				   LEFT JOIN profiles ON profiles.profile_id = enrollments.e_profile_id
				   WHERE e_grade_level IN ({$level_ids})
				   AND verified = 1
				   AND registrar_approved = 1
				   AND e_ay_id = ?";
		$q = $this->db->query($l_eids,[$this->c_sy->id]);

		if($q->num_rows() >=1 )
		{
			foreach ($q->result() as $key => $value) {
				$e_ids[$key] = $value->e_id;
			}
			return $e_ids;
		}else{
			return FALSE;
		}
	}

	private function _process_section($sections)
	{
		$section_ids = "'". implode("', '", $sections) ."'";

		$l_eids = "SELECT e_id
				   FROM enrollments
				   LEFT JOIN profiles ON profiles.profile_id = enrollments.e_profile_id
				   WHERE e_section_id IN ({$section_ids})
				   AND verified = 1
				   AND registrar_approved = 1
				   AND e_ay_id = ?";
		$q = $this->db->query($l_eids,[$this->c_sy->id]);
		
		if($q->num_rows() >=1 )
		{
			foreach ($q->result() as $key => $value) {
				$s_ids[$key] = $value->e_id;
			}
			return $s_ids;
		}else{
			return FALSE;
		}
	}

	private function _process_student($student)
	{
		pp('students');
		pd($student);
	}

	private function _process_employees()
	{
		$l_eids = '';
	}


	private function _get_name($id,$type)
	{
		if($type == 'student')
		{
			$get_name = 'SELECT concat_ws("",p.firstname," ",p.lastname) as fullname
							FROM enrollments e
							LEFT JOIN profiles p ON p.profile_id = e.e_profile_id
							WHERE e.e_profile_id = ?
							LIMIT 1';

		}else if($type == 'guardian'){
			$get_name ='SELECT username as fullname
					   FROM users
					   WHERE id = ?
					   LIMIT 1';
		}else{
			$get_name ='SELECT concat_ws("",emp.first_name," ",emp.last_name) as fullname
					   FROM employees emp
					   WHERE emp_id = ?
					   LIMIT 1';

		}

		$rget_name = $this->db->query($get_name,[$id]);
		return $rget_name->num_rows() >= 1 ? $rget_name->row()->fullname : ' -no name- ';
	}

	public function inbox()
	{
		$emp_id = $this->c_user->emp_id;

		$get_thread = "SELECT DISTINCT mp.thread_id
					FROM message_person mp
					LEFT JOIN message_thread mt ON mt.id = mp.thread_id
					WHERE mp.user = ?
					AND mp.del = ?
					ORDER BY mt.created DESC";
		$q_thread = $this->db->query($get_thread,[$emp_id,'no']);
		
		if($q_thread->num_rows() >=1 )
		{
			foreach($q_thread->result() as $k => $v)
			{
				$array[$k]['data'] = $this->_inbox($v->thread_id);
				$array[$k]['recipients'] = $this->_inbox_recipients($v->thread_id,$emp_id);
			}

			return $array;
		}else{
			return FALSE;
		}
		
	}

	private function _inbox($thread = '')
	{
		$message = "SELECT *,mt.senders_name as origin,
						   DATE_FORMAT(mt.created,'%M %d , %Y - %l:%i %p') as msg_created
					FROM message_thread mt
					LEFT JOIN message_person mp ON mp.thread_id = mt.id
					WHERE mt.status = 'open'
					AND mt.id = ? 
					";

		$q_message = $this->db->query($message,[$thread]);
		return $q_message->num_rows() >=1 ? $q_message->row() : FALSE;
	}

	private function _inbox_recipients($thread = '',$except = '')
	{
		$message = "SELECT mp.senders_name as recipient
					FROM message_thread mt
					LEFT JOIN message_person mp ON mp.thread_id = mt.id
					WHERE mt.status = 'open'
					AND mp.thread_id = ?
					AND mp.del = ?
					AND mp.user != mt.sender_id";

		$q_message = $this->db->query($message,[$thread,'no']);
		return $q_message->num_rows() >=1 ? $q_message->result() : FALSE;
	}
	
	public function delbox()
	{
		$emp_id = $this->c_user->emp_id;

		$get_thread = "SELECT DISTINCT mp.thread_id
					FROM message_person mp
					LEFT JOIN message_thread mt ON mt.id = mp.thread_id
					WHERE mp.user = ?
					AND mp.del = ?
					ORDER BY mt.created DESC";
		$q_thread = $this->db->query($get_thread,[$emp_id,'yes']);

		if($q_thread->num_rows() >=1 )
		{
			foreach($q_thread->result() as $k => $v)
			{
				$array[$k]['data'] = $this->_delbox($v->thread_id);
				$array[$k]['recipients'] = $this->_delbox_recipients($v->thread_id,$emp_id);
			}

			return $array;
		}else{
			return FALSE;
		}
	}
	
	private function _delbox($thread = '')
	{
		$message = "SELECT *,mt.senders_name as origin,
						   DATE_FORMAT(mt.created,'%M %d , %Y - %l:%i %p') as msg_created
					FROM message_thread mt
					LEFT JOIN message_person mp ON mp.thread_id = mt.id
					WHERE mt.status = 'open'
					AND mt.id = ? 
					";

		$q_message = $this->db->query($message,[$thread]);
		return $q_message->num_rows() >=1 ? $q_message->row() : FALSE;
	}
	
	private function _delbox_recipients($thread = '',$except = '')
	{
		$message = "SELECT mp.senders_name as recipient
					FROM message_thread mt
					LEFT JOIN message_person mp ON mp.thread_id = mt.id
					WHERE mt.status = 'open'
					AND mp.thread_id = ?
					AND mp.user != mt.sender_id";

		$q_message = $this->db->query($message,[$thread]);
		return $q_message->num_rows() >=1 ? $q_message->result() : FALSE;
	}
	
	public function set_read($thread)
	{
		$emp_id = $this->c_user->emp_id;
		
		$sqlUpdate = "UPDATE message_person 
					  SET new='no' 
					  WHERE thread_id = ? 
					  AND user = ?
					 "; 
		
		$this->db->query($sqlUpdate,[$thread,$emp_id]);
	}

	public function sentbox()
	{
		$emp_id = $this->c_user->emp_id;

		$message = 'SELECT *
					FROM message_thread mt
					LEFT JOIN message_person mp ON mp.thread_id = mt.id
					WHERE user = ?
					AND mt.sender_id = ?
					AND mt.status = "open"
					GROUP BY thread_id
					ORDER BY mt.created';
		$q = $this->db->query($message,[$emp_id,$emp_id]);

		return $q->num_rows() >=1 ? $q->result() : FALSE;
	}

	public function show_thread($id)
	{
		$sql = 'SELECT * ,date_format(created,"%M %d, %Y, %h:%i %p") as created_on
				FROM message_data md
				LEFT JOIN message_person mu ON md.created_by = mu.user AND mu.type = md.type
				WHERE md.thread_id = ?
				GROUP BY md.id
				ORDER BY md.created DESC';
		$q = $this->db->query($sql,[$id]);

		return $q->num_rows() >=1 ? $q->result() : FALSE;
	}

	public function reply_to_thread($post)
	{
		// pd($post);

		$message_data['contents'] = htmlentities($post['message_body']);
		$message_data['attachments'] = '';
		$message_data['thread_id'] = $post['thread_id'];
		$message_data['created'] = NOW;
		$message_data['created_by'] = $this->c_user->emp_id;
		$message_data['type'] ='employee';

		$this->db->insert('message_data',$message_data);

		return $this->db->affected_rows() >=1 ? TRUE :FALSE;
	}
	
	//all messages regardless of ID
	public function allinbox()
	{
		$get_thread = 'SELECT senders_name as origin, id, sender_id
					FROM message_thread
					WHERE del = ?
					ORDER BY created DESC';
		$q_thread = $this->db->query($get_thread,'no');
		
		//vd($q_thread->result());
		
		if($q_thread->num_rows() >=1 )
		{
			foreach($q_thread->result() as $k => $v)
			{
				$array[$k]['data'] = $this->_allinbox($v->id);
				$array[$k]['recipients'] = $this->_allinbox_recipients($v->id,$v->sender_id);
			}

			return $array;

		}else{
			return FALSE;
		}
		
	}
	
	private function _allinbox($thread = '')
	{
		$message = "SELECT *,senders_name as origin,
						   DATE_FORMAT(created,'%M %d , %Y - %l:%i %p') as msg_created
					FROM message_thread
					WHERE id = ? ";

		$q_message = $this->db->query($message,[$thread]);
		return $q_message->num_rows() >=1 ? $q_message->row() : FALSE;
	}
	
	private function _allinbox_recipients($thread = '',$except = '')
	{
		$message = "SELECT mp.senders_name as recipient
					FROM message_thread mt
					LEFT JOIN message_person mp ON mp.thread_id = mt.id
					WHERE mt.status = 'open'
					AND mp.thread_id = ?
					AND mp.user != ?";

		$q_message = $this->db->query($message,[$thread,$except]);
		return $q_message->num_rows() >=1 ? $q_message->result() : FALSE;
	}
	
	public function my_unread_message()
	{
		$sql = "SELECT count(DISTINCT mp.thread_id) as num_rows
	                FROM message_data md
					LEFT JOIN message_person mp ON mp.thread_id = md.thread_id
					LEFT JOIN message_thread mt ON md.thread_id = mt.id
					WHERE mp.new = ?
					AND mt.del = ?
					AND mp.user = ? 
					AND md.created_by != ? 
					";
		
		$query = $this->db->query($sql,['yes','no',$this->c_user->emp_id,$this->c_user->emp_id]);
		
		return $query->num_rows() >= 1 ? $query->row()->num_rows : FALSE;
	}
	
	public function remove_me($thread = '')
	{
		$emp_id = $this->c_user->emp_id;
		
		$sqlUpdate = "UPDATE message_person, message_thread
						SET message_person.del = 'yes',
							message_thread.del = 'yes'
						WHERE message_person.thread_id = message_thread.id
						AND message_thread.id = ?
						AND message_person.thread_id = ?
					 "; 
		
		$this->db->query($sqlUpdate,[$thread,$thread]);
		
		return $this->db->affected_rows() >=1 ? TRUE :FALSE;
	}
	
	public function remove_me_also($thread = '')
	{
		$emp_id = $this->c_user->emp_id;
		
		$sqlUpdate = "UPDATE message_person, message_thread
						SET message_person.del = 'yes'
						WHERE message_person.thread_id = message_thread.id
						AND message_person.thread_id = ?
						AND message_person.user = ?
					 "; 
		
		$this->db->query($sqlUpdate,[$thread,$emp_id]);
		
		return $this->db->affected_rows() >=1 ? TRUE :FALSE;
	}
	
	public function remove_me_permanently($thread = '')
	{
		$emp_id = $this->c_user->emp_id;
		
		$sql = "SELECT mp.user
	                FROM message_person mp
					LEFT JOIN message_thread mt ON mp.thread_id = mt.id
					WHERE mp.user != ? 
					AND mp.thread_id = ?
					AND mp.user != mt.sender_id
					";
					
		$query = $this->db->query($sql,[$emp_id,$thread]);

		if($query->num_rows() >= 1){
			$sqlDelete = "DELETE FROM message_person
							WHERE user = ?
							AND thread_id = ? 
						 ";
						 
			$this->db->query($sqlDelete,[$emp_id,$thread]);
			
			if($this->db->affected_rows() >=1){
				$sqlDelete2 = "DELETE FROM message_data
							WHERE created_by = ?
							AND thread_id = ?
						 ";
						 
				$this->db->query($sqlDelete2,[$emp_id,$thread]);
				
				return TRUE;
			}else{
				return FALSE;
			}
		}else{
			$sqlDelete = "DELETE FROM message_person
							WHERE thread_id = ?
						 ";
						 
			$this->db->query($sqlDelete,[$thread]);
			
			if($this->db->affected_rows() >=1){
				$sqlDelete2 = "DELETE FROM message_data
							WHERE thread_id = ?
						 ";
						 
				$this->db->query($sqlDelete2,[$thread]);
				
				$sqlDelete3 = "DELETE FROM message_thread
							WHERE id = ?
						 ";
						 
				$this->db->query($sqlDelete3,[$thread]);
				
				return TRUE;
			}else{
				return FALSE;
			}
		}
	}

	/**
	 * Count Person that are viewing the thread
	 */
	public function count_viewer($thread_id)
	{
		$sql = "SELECT count(id) as c FROM message_person WHERE thread_id = ? AND del = ?"; 
		return $this->query($sql, [$thread_id,'no'], true)->c;
	}
}